<?php

namespace App\Jobs;

use App\Mail\ExceptionNotifyEmail;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;

/**
 * 异常不能再抛出，不会继续走全局异常处理，导致死循环
 */
class ExceptionNotifyJob extends BaseJob
{
    /* @var string 名称 */
    protected $name = 'ExceptionNotifyJob';
    /* @var string 描述 */
    protected $description = '异常通知';
    /* @var bool 是否需要异常通知 */
    protected $needExceptionNotify = false;

    public $queue = 'exception-notify'; // 指定队列名称

    /* @var array 非唯一值需要 public 方法，否则在对象输出时识别不了唯一性 */
    public $params = [
        'exception' => '',
        'message' => '',
        'file' => '',
        'line' => '',
        'trace' => '',
        'source' => '',
        'context' => '',
    ];

    /* @var string 唯一值需要非 public 方法 */
    protected $traceId;

    public function __construct($params, $traceId)
    {
        $this->params = $params;
        $this->traceId = $traceId;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    protected function handleExec()
    {
        $this->sendEmail();
    }

    /**
     * 发送邮件
     */
    protected function sendEmail()
    {
        $coolTime = config('app.exception_notify.email.cool_time');
        // 计算内容唯一值
        $content = unserialize($this->job->payload()['data']['command']);
        $contentString = json_encode($content);
        $md5 = md5($contentString);

        $cacheKey = 'exception-notify-email.' . $md5;
        if (Cache::has($cacheKey)) {
            Log::info('邮件异常通知发送冷却中......');
            return;
        }
        Mail::send(new ExceptionNotifyEmail($this->params, $this->traceId));

        Cache::put($cacheKey, $this->uuid, $coolTime);

        Log::info('邮件异常通知已发送');
    }
}
